package com.assisjrs.jpaandroid.persistence.converter;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.database.Cursor;

import com.assisjrs.jpaandroid.persistence.ConverterDatabase;
import com.assisjrs.jpaandroid.persistence.Entity;

public class DateConverter implements ConverterDatabase<Date, String> {
	private static final String DATE_FORMAT = "yyyy-MM-dd";
	private final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

	public String getFromInstance(final Field field, final Entity entity) {
		try {
			final Date value = (Date) field.get(entity);

			if (value == null)
				return "";

			return dateFormat.format(value);
		} catch (final IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (final IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@SuppressWarnings("deprecation")
	public Date getToInstance(final Cursor cursor, final int columnIndex, final Class<?> type) {
		final String value = cursor.getString(columnIndex);

		if (value == null || "".equals(value.trim()))
			return null;

		try {
			final Date data = dateFormat.parse(value);

			return new java.sql.Date(data.getYear(), data.getMonth(), data.getDate());
		} catch (final ParseException e) {
			throw new RuntimeException(e);
		}
	}
}
